package com.example.ggpicturegg.bottom;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.example.ggpicturegg.Mysql_com.ImageDao;
import com.example.ggpicturegg.Mysql_com.ImageInfo;
import com.example.ggpicturegg.Mysql_com.Userinfo;
import com.example.ggpicturegg.R;
import com.example.ggpicturegg.first.RecyclerviewActivity;
import com.example.ggpicturegg.ftpUD.UpAndDown;
import com.example.ggpicturegg.tool.BlobAndBytes;
import com.example.ggpicturegg.tool.CommonUtils;
import com.example.ggpicturegg.tool.Loaddata;
import com.mysql.jdbc.Blob;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import org.w3c.dom.Document;

import java.security.PrivateKey;
import java.util.ArrayList;
import java.util.HashMap;

import javax.net.ssl.ManagerFactoryParameters;

public class Publish_b extends AppCompatActivity {

    public static final int CHOOSER_PICTURE = 2;
    private EditText set_tilte;
    private EditText set_desc;
    private ImageView set_image;
    private ImageView btn_back;
    private ImageView btn_isok;
    private Uri imageUri;
    private ImageView get_image;
    private int ans=0;
    private String firePath_local;


    private Bitmap imageBlol_all;
    private Handler mainHandler;
    private ImageDao imageDao;

    private Bundle Pbundle;
    private String s = null;


    private static final int REQUEST_CODE_SELECT_IMAGE = 4;
    private static final int REQUEST_CODE_STORAGE_PERMISSION = 5;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_b);

        initView();
        transinfo();

    }

    private void transinfo(){
        Pbundle = getIntent().getExtras();
        s = Pbundle.getString("Re_to_add");
        if(s!=null){ Log.d("Publish 接受 Re 的name", "    ---------- is ---------    "+ s);}
        if(s==null){
            s = Pbundle.getString("friend_to_add");
            if(s!=null){Log.d("Publish 接受 friend 的name", "    ---------- is ---------    "+ s);}
        }
        if(s==null){
            s = Pbundle.getString("talk_to_add");
            if(s!=null){Log.d("Publish 接受 talk 的name", "    ---------- is ---------    "+ s);}
        }
        if(s==null){
            s = Pbundle.getString("like_to_add");
            if(s!=null){Log.d("Publish 接受 like 的name", "    ---------- is ---------    "+ s);}
        }
        if(s==null){
            s = Pbundle.getString("care_to_add");
            if(s!=null){ Log.d("Publish 接受 care 的name", "    ---------- is ---------    "+ s);}
        }
    }

    private void initView(){

        set_tilte = findViewById(R.id.set_title);
        set_desc   = findViewById(R.id.set_desc);
        set_image  = findViewById(R.id.set_image);
        btn_back   = findViewById(R.id.btn_return);
        btn_isok  = findViewById(R.id.btn_isok_add);
        get_image=(ImageView)findViewById(R.id.get_image);
        OnClick onClick = new OnClick();
        mainHandler = new Handler(getMainLooper());      //获取主线程
        imageDao = new ImageDao();
        //ans = imageDao.getImage_max_id() + 1;
        set_image.setOnClickListener(onClick);
        btn_back.setOnClickListener(onClick);
        btn_isok.setOnClickListener(onClick);
    }



    // 增加照片
    private  void AddImage(){
        if( (ContextCompat.checkSelfPermission(Publish_b.this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED))
        {
            ActivityCompat.requestPermissions(Publish_b.this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},1);
        }else {
            openAlbum();
        }
    }

    //自动打开相册
    private void openAlbum() {
        Intent intent =new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,CHOOSER_PICTURE);
    }

    // 选择图片
    private void selectImage() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(intent, REQUEST_CODE_SELECT_IMAGE);
        }
    }

    // 处理权限申请结果
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if (grantResults.length >0&&grantResults[0]==PackageManager.PERMISSION_GRANTED){
                    openAlbum();
                }else {
                    Toast.makeText(Publish_b.this,"用户拒绝你的权限请求",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_STORAGE_PERMISSION && grantResults.length > 0) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                selectImage();
            } else {
                Toast.makeText(this, "没有权限!", Toast.LENGTH_SHORT).show();
            }
        }
    }

    //
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        switch (requestCode){
            case CHOOSER_PICTURE:
                if (resultCode==RESULT_OK){
                    if(Build.VERSION.SDK_INT>=19){
                        handleImageOnKitkat(data);
                    }else {
                        handleImagebeforeKitkat(data);
                    }
                }
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

//获取sdk小于19的访问权
    private void handleImagebeforeKitkat(Intent data) {
        Uri uri=data.getData();
        String imagepath=getimagepath(uri,null);
        firePath_local = imagepath;
        System.out.println("-------------imagepath ----------is    "+imagepath);
        displayImage(imagepath);
    }

//获取sdk版本大于19的访问权限
@TargetApi(19)
    private void handleImageOnKitkat(Intent data) {
        String imagepath=null;
        Uri uri=data.getData();
        if(DocumentsContract.isDocumentUri(this,uri)){
            String docId=DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id=docId.split(":")[1];
                String selection=MediaStore.Images.Media._ID+"="+id;
                imagepath=getimagepath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,selection);
            }else if ("com.android.providers.downlo ads.documents".equals(uri.getAuthority())){
                        Uri contentUri= ContentUris.withAppendedId(Uri.parse("content://downloads"),Long.valueOf(docId));
                        imagepath=getimagepath(contentUri,null);
            }else if ("content".equalsIgnoreCase(uri.getScheme())){
                imagepath=getimagepath(uri,null);
            }else if("file".equalsIgnoreCase(uri.getScheme())){
                imagepath=uri.getPath();

            }
            System.out.println("-------------imagepath ----------is    "+imagepath);
            firePath_local = imagepath;
            displayImage(imagepath);

        }
    }

//展示图片
    private void displayImage(String imagepath) {
        if (imagepath!=null){
            Bitmap bitmap= BitmapFactory.decodeFile(imagepath);
            imageBlol_all = bitmap;
            get_image.setImageBitmap(bitmap);
        }else {
            Toast.makeText(this,"用户选择图像失败",Toast.LENGTH_SHORT).show();
        }
    }

//获取图片路径
    private String getimagepath(Uri uri, String selection) {
        String path=null;
        Cursor cursor=getContentResolver().query(uri,null,selection,null,null);
        if(cursor!=null){
            if (cursor.moveToNext()){
                path=cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
            return path;
    }

// 执行分享确定操作
    private String doShare(String filename1){
        ImageInfo item = new ImageInfo();
        final String title = set_tilte.getText().toString().intern();
        final String desc  =  set_desc.getText().toString().intern();
        if(TextUtils.isEmpty(title)){
            CommonUtils.showShortMsg(this,"请输入标题");
            set_tilte.requestFocus();
        }else if(TextUtils.isEmpty(desc)){
            CommonUtils.showShortMsg(this,"请输入描述");
            set_desc.requestFocus();
        }else{
            Bundle bundle1 = getIntent().getExtras();
            int ttt = bundle1.getInt("max_id");
            String s = bundle1.getString("Re_to_add");
            Log.d("--Publish 接受 Re 的值-- is", "          "+ s);
            ttt = ttt + 1;
            item.setX_coutn(0);
            item.setPicture_name(filename1);
            item.setX_name(s);
            item.setId(ttt);
            item.setX_title(title);
            item.setDesc(desc);

            String ss = item.getX_name()+" "+item.getId() + " "+item.getDesc();
            Log.d("Add..12  name and id ", ss);
            Log.d("Add..12484534643", "doShare: is   ok ");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final int iRow = imageDao.addImage(item);
                    /*
                    System.out.println("-------------id ----------is              "+item.getId());
                    System.out.println("-------------Picture_name ----------is    "+item.getPicture_name());
                    System.out.println("-------------user_name ----------is       "+item.getX_name());
                    System.out.println("-------------title ----------is           "+item.getX_title());
                    System.out.println("-------------点赞 ----------is             "+item.getX_coutn());
                    System.out.println("-------------描述----------is              "+item.getDesc());
                     */

                    UpAndDown.ftpUpload(firePath_local,filename1,item.getId());
                }
            }).start();

        }
        return item.getX_name();
    }



    class OnClick implements View.OnClickListener{
        private Intent intent;
        private Bundle bundle;

        @Override
        public void onClick(View v) {

            bundle = new Bundle();
            switch (v.getId()){
                case R.id.btn_return:
                    intent = new Intent(Publish_b.this, RecyclerviewActivity.class);
                    bundle = new Bundle();
                    bundle.putString("public_return_name",s);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    break;
                case R.id.set_image:
                    //添加图片
                    AddImage();
                    break;
                case R.id.btn_isok_add:
                    // 发布
                    String[] words=firePath_local.split("/");
                    int len = words.length - 1;
                    System.out.println("-------------file ----------is    "+words[len]);
                    String fireName_local = words[len];
                    String name = doShare(fireName_local);
                    Log.d("from Re to Publish  ", "    ---------- is ---------    "+ name);
                    CommonUtils.showShortMsg(Publish_b.this,"发布完成！！！");
                    intent = new Intent(Publish_b.this,RecyclerviewActivity.class);
                    bundle.putString("public_ok_to_Re_name",name);
                    intent.putExtras(bundle);
                    startActivity(intent);
                    break;
            }
        }
    }

}